#!/bin/bash
# Copyright (c) 2023-2024 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

usage() {
printf "query what requires the specify package

usage:
    bash rpm_whatrequires.sh [-h | --help] [PACKAGES | PKGFILE]

arguments:
    PACKAGE        rpm package name
    PKGFILE        file include rpm package name

optional arguments:
    -h, --help     show the help message and exit
\n"
}

get_list() {
    local lst=""

    if [ -f "$1" ]; then
        lst=$(cat $1)
    else
        lst=$1
    fi

    echo $lst
}


main() {
    if [[ $# -lt 1 || "$1" = "-h" || "$1" = "--help" ]]; then
        usage; exit 1
    fi
    local pkgs=$(get_list "$1")
    echo "BasePackage,Type,RequiredByPackage,From,SRPM"
    for pkg in $pkgs; do
        local wreqs=$(dnf repoquery -q --whatrequires $pkg)
        for req in $wreqs; do
            local req_type="install"
            if [[ $req =~ src$ ]]; then
                req_type="build"
            fi
            dnf repoquery -q --requires $req | grep -q $pkg
            if [ $? -ne 0 ]; then
                continue
            fi
            local info=$(dnf repoquery -q -i $req)
            local src_name="$req"
            if [ $req_type == "install" ]; then
                src_name=$(echo "$info" | grep -E "^Source.*\.src\.rpm$" | head -n1 | awk '{print $NF}')
            fi
            src_name=$(echo $src_name | sed -r 's/-[^-]+-[^-]+$//')
            local from_repo=$(echo "$info" | grep -E "^Repository" | head -n1 | awk '{print $NF}')
            echo "$pkg,$req_type,$req,$from_repo,$src_name"
        done
    done
}

main "$@"
